package com.jcli._socket基恩士客户端;

import com.jcli.HslCommunication.HslCommunicationDemo.DemoUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;

public class SocketClientHsl extends JFrame {
    private JTextField ipField; // IP 地址文本框
    private JTextField portField; // 端口号文本框
    private JButton connectButton; // 连接按钮
    private JButton disconnectButton; // 断开连接按钮
    private JTextArea receivedDataArea; // 用于显示接收到的数据的文本区域
    private Socket socket; // Socket 对象，用于建立连接
    private PrintWriter out; // 用于发送数据的 PrintWriter
    private BufferedReader in; // 用于接收数据的 BufferedReader

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("[HH:mm:ss] ");

    private JTextArea textArea;
    private int readCount; // 读取计数器
    private boolean isReading; // 用于标识是否正在读取

    // 构造函数，初始化界面和组件
    public SocketClientHsl() {
        // 设置窗口标题和关闭操作
        setTitle("Socket Client");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 300);
        setLocationRelativeTo(null); // 设置窗口居中

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout());

        JLabel ipLabel = new JLabel("IP:");
        ipField = new JTextField(10);
        ipField.setText("192.168.10.10");

        JLabel portLabel = new JLabel("Port:");
        portField = new JTextField(5);
        portField.setText("8500");

        connectButton = new JButton("Connect");
        disconnectButton = new JButton("Disconnect");
        disconnectButton.setEnabled(false);

        topPanel.add(ipLabel);
        topPanel.add(ipField);
        topPanel.add(portLabel);
        topPanel.add(portField);
        topPanel.add(connectButton);
        topPanel.add(disconnectButton);

        receivedDataArea = new JTextArea();
        receivedDataArea.setEditable(false);

        JScrollPane scrollPane = new JScrollPane(receivedDataArea);

        add(topPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);

        connectButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                // 检查按钮是否被禁用，如果被禁用则不执行后续操作
                if (connectButton.isEnabled() == false) return;
                super.mouseClicked(e);  // 调用父类的 mouseClicked 方法
                connect();
            }
        });


        disconnectButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (disconnectButton.isEnabled() == false) return; // 如果断开按钮被禁用，不执行后续操作
                disconnect();
            }
        });
    }

    private void connect() {
        // 获取用户输入的 IP 地址和端口号
        String ip = ipField.getText();
        int port = Integer.parseInt(portField.getText());

        try {
            // 创建 PrintWriter 和 BufferedReader 对象，用于数据的发送和接收
            socket = new Socket(ip, port);
            // 创建 PrintWriter 和 BufferedReader 对象，用于数据的发送和接收
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 初始化计数器和读取状态
            readCount = 0;
            isReading = false;

            if (socket.isConnected()) { // 如果连接成功
                // 连接成功时，显示成功消息框
                JOptionPane.showMessageDialog(
                        null,
                        "Connect Success", // 消息框的消息内容
                        "Result", // 消息框标题
                        JOptionPane.PLAIN_MESSAGE); // 消息框类型为普通消息

                // 启用内容区域的 UI 元素，通常是在连接成功后才允许用户进行其他操作
                // DemoUtils.SetPanelEnabled(panelContent, true); // 启用内容区域的UI元素
                connectButton.setEnabled(true);  // 启用断开连接按钮
                disconnectButton.setEnabled(false); // 禁用当前连接按钮，避免重复连接

                // 启动一个新线程，用于接收服务器发送的数据并在文本区域中显示
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String receivedData;
                            while ((receivedData = in.readLine()) != null) {
                                receivedDataArea.append(receivedData + "\n");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            } else {
                // 连接失败时，显示失败消息框
                JOptionPane.showMessageDialog(
                        null,
                        "Connection failed.",
                        "Error",
                        JOptionPane.WARNING_MESSAGE); // 消息框类型为警告消息
            }
        } catch (IOException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(
                    null,
                    "Connect Failed\r\nReason:" + e.getMessage(), // 显示错误原因
                    "Error",
                    JOptionPane.ERROR_MESSAGE); // 消息框类型为错误消息
        }
    }

    private void disconnect() {
        try {
            // 关闭 BufferedReader、PrintWriter 和 Socket 对象
            if (in != null)
                in.close();
            if (out != null)
                out.close();
            if (socket != null)
                socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        connectButton.setEnabled(true);
        disconnectButton.setEnabled(false);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                SocketClientHsl client = new SocketClientHsl();
                client.setVisible(true);
            }
        });
    }
}
